package com.javaweb.oa02.user;

import com.javaweb.oa02.util.DButil;
import com.javaweb.oa02.web.action.userSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/welcome")
public class welcome extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Cookie[] cookies= req.getCookies();
        String username=null;
        String password=null;

        if(cookies!=null){
            for(Cookie cookie:cookies){
                String name=cookie.getName();
             if("username".equals(name)){
                 username=cookie.getValue();
                }else if("password".equals(name)){
                 password=cookie.getValue();
             }
            }
        }
        boolean success = false;
        if(username!=null && password!=null) {
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;

            try {
                conn = DButil.getConnection();
                String sql = "select * from user where username=? and password=?";
                ps = conn.prepareStatement(sql);
                ps.setString(1, username);
                ps.setString(2, password);
                rs = ps.executeQuery();
                if (rs.next()) {
                    success = true;
                }

            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                DButil.close(conn, ps, rs);
            }
        }

            if(success){
                HttpSession session= req.getSession();
                //将username存入session域，后面用来做入口验证
                session.setAttribute("username",username);
                //如果登录成功，存userSession促发监听
                userSession user1= new userSession(username,password);
                session.setAttribute("user",user1);

                resp.sendRedirect(req.getContextPath()+"/dept/list");
            }else{
                resp.sendRedirect(req.getContextPath()+"/index.jsp");
            }



    }
}
